package com.sxm.yiwei.activitis;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BookPayActivity;
import com.sxm.yiwei.tools.CallPhone;
import com.sxm.yiwei.tools.CastTime;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class FWBookContentActivity extends BaseActivity implements View.OnClickListener{

    private ImageView otherback;
    private LinearLayout othersearch;
    private ImageView backmain;
    private TextView bookstate;
    private TextView fwbookamount;
    private TextView fwbookname;
    private TextView fwbookstate;
    private TextView fwbookvendor;
    private TextView fwbookbuyer;
    private TextView fwvendorad;
    private TextView fwbuyerad;
    private ImageView fwimg;
    private TextView fwname;
    private TextView fwother;
    private TextView fwnumber;
    private TextView fwprice;
    private TextView fwTamount;
    private TextView fwbookcode;
    private TextView fwbookbuytime;
    private TextView weiyuixia;
    private TextView call;
    private int from;
    private String contactPhone;
    private String userMobile;
    private Button fwbookbetween;
    private Button fwbookright;
    private Button fwbookleft;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private String id;
    private double totalAmount;
    private String avatar,shopName,orderPayTime,orderPayType;
    private TextView fwbook;
    private TextView fwbookt;
    private TextView fwpaytype;
    private TextView fwpaytypet;
    private TextView fwpaytime;
    private TextView fwpaytimet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fw_other);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");

        initOtherView();
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        String contactHouseNumber = intent.getStringExtra("contactHouseNumber");
        shopName = intent.getStringExtra("shopName");
        orderPayTime = intent.getStringExtra("orderPayTime");
        orderPayType = intent.getStringExtra("orderPayType");
        contactPhone = intent.getStringExtra("contactPhone");
        String message = intent.getStringExtra("message");
        String makeupAmount = intent.getStringExtra("makeupAmount");
        avatar = intent.getStringExtra("avatar");
        String contactAddress = intent.getStringExtra("contactAddress");
        String contactName = intent.getStringExtra("contactName");
        String name = intent.getStringExtra("name");
        userMobile = intent.getStringExtra("userMobile");
        String orderCode = intent.getStringExtra("orderCode");
        String shopAddress = intent.getStringExtra("shopAddress");
        double amount = intent.getDoubleExtra("amount", 0.0);
        totalAmount = intent.getDoubleExtra("totalAmount", 0.0);
        long buyTime = intent.getLongExtra("buyTime", 1);
        long commentTime = intent.getLongExtra("commentTime", 1);
        int makeupCount = intent.getIntExtra("makeupCount", 0);
        int count = intent.getIntExtra("count", 0);
        from = intent.getIntExtra("from", 1);

        if (from ==11){
            bookstate.setText("买家-待付款");
            fwbookstate.setText("待付款");
            fwbookright.setText("立即支付");
            fwbookbetween.setText("删除订单");
            fwbookleft.setVisibility(View.GONE);
            fwpaytime.setVisibility(View.GONE);
            fwpaytimet.setVisibility(View.GONE);
            fwpaytype.setVisibility(View.GONE);
            fwpaytypet.setVisibility(View.GONE);
        }else if (from ==12){
            bookstate.setText("买家-待服务");
            fwbookstate.setText("待服务");
            fwbookright.setText("加价");
            fwbookbetween.setText("取消订单");
            fwbookleft.setVisibility(View.GONE);
        }else if (from ==13){
            bookstate.setText("买家-服务中");
            fwbookstate.setText("服务中");
            fwbookright.setText("加价");
            fwbookbetween.setText("申诉");
            fwbookleft.setVisibility(View.GONE);
        }else if (from ==14){
            bookstate.setText("买家-待完结");
            fwbookstate.setText("待完结");
            fwbookright.setText("服务完结");
            fwbookbetween.setText("加价");
            fwbookleft.setText("申诉");
        }else if (from ==15){
            bookstate.setText("买家-已完结");
            fwbookstate.setText("已完结");
            fwbookright.setText("评价");
            fwbookbetween.setText("申诉");
            fwbookleft.setVisibility(View.GONE);
        }else if (from ==16){
            bookstate.setText("买家-异常订单");
            fwbookstate.setText("异常订单");
            fwbookright.setText("回复");
            fwbookleft.setVisibility(View.GONE);
            fwbookbetween.setVisibility(View.GONE);
        }else if (from ==21){
            bookstate.setText("卖家-待服务");
            fwbookstate.setText("待服务");
            fwbookright.setText("开始服务");
            fwbookbetween.setText("加价");
            fwbookleft.setText("取消订单");
        }else if (from ==22){
            bookstate.setText("卖家-服务中");
            fwbookstate.setText("服务中");
            fwbookright.setText("服务完成");
            fwbookbetween.setText("加价");
            fwbookleft.setText("申诉");
        }else if (from ==23){
            bookstate.setText("卖家-待完结");
            fwbookstate.setText("待完成");
            fwbookright.setText("加价");
            fwbookbetween.setText("申诉");
            fwbookleft.setVisibility(View.GONE);
        }else if (from ==24){
            bookstate.setText("卖家-已完成");
            fwbookstate.setText("已完成");
            fwbookright.setText("回复");
            fwbookbetween.setText("申诉");
            fwbookleft.setVisibility(View.GONE);
        }else if (from ==25){
            bookstate.setText("卖家-异常订单");
            fwbookstate.setText("异常订单");
            fwbookright.setText("回复");
            fwbookleft.setVisibility(View.GONE);
            fwbookbetween.setVisibility(View.GONE);
        }
        fwbookcode.setText(orderCode);
        fwbookname.setText(name);
        fwname.setText(name);
        Integer paytype = Integer.valueOf(orderPayType);
        switch (paytype){
            case 0:
                fwpaytypet.setText("未付款");
                break;
            case 1:
                fwpaytypet.setText("支付宝");
                break;
            case 2:
                fwpaytypet.setText("微信");
                break;
            case 3:
                fwpaytypet.setText("余额");
                break;
        }

        fwpaytimet.setText(CastTime.startTime(Long.valueOf(orderPayTime)));
        fwprice.setText(amount+" 元/单");
        fwTamount.setText(totalAmount +" 元");
        fwbookvendor.setText(userMobile);
        fwvendorad.setText(shopAddress);
        fwbuyerad.setText(contactAddress+" "+contactHouseNumber);
        fwbookbuyer.setText(contactName +" "+ contactPhone);
        if (from==11){
            fwbookamount.setText("待付款 "+totalAmount +" 元");
        }else {
            if (makeupCount==0){
                fwbookamount.setText("");
            }else {
                fwbookamount.setText("加价 "+makeupCount+"次");
            }

        }
        if (message!=null){
            fwother.setText(message);
        }else {}
        if (count==0){

        }else {
            fwnumber.setText("数量 :"+count);
        }

        fwbookbuytime.setText(CastTime.startTime(buyTime));
        x.image().bind(fwimg, InternetAddressUtis.IMG_URL+ avatar);
    }

    private void initOtherView() {
        otherback = (ImageView) findViewById(R.id.other_back);
        backmain = (ImageView) findViewById(R.id.fwbookcontent_backmain);
        bookstate = (TextView) findViewById(R.id.fwbookcontent_state);

        fwbookamount = (TextView) findViewById(R.id.fwbook_amount);
        fwbookname = (TextView) findViewById(R.id.fwbook_buyername);
        fwbookstate = (TextView) findViewById(R.id.fwbook_bookstate);
        fwbookvendor = (TextView) findViewById(R.id.fwbook_vendor);
        fwbookbuyer = (TextView) findViewById(R.id.fwbook_buyer);
        fwvendorad = (TextView) findViewById(R.id.fwbook_vendor_ad);
        fwbuyerad = (TextView) findViewById(R.id.fwbook_buyer_ad);
        fwimg = (ImageView) findViewById(R.id.fwbook_fwimg);
        fwname = (TextView) findViewById(R.id.fwbook_fwname);
        fwother = (TextView) findViewById(R.id.fwbook_fwother);
        fwnumber = (TextView) findViewById(R.id.fwbook_number);
        fwprice = (TextView) findViewById(R.id.fwbook_price);
        fwTamount = (TextView) findViewById(R.id.fwbook_tamount);
        fwbookcode = (TextView) findViewById(R.id.fwbook_bookcodet);
        fwbookbuytime = (TextView) findViewById(R.id.fwbook_booktimet);
        weiyuixia = (TextView) findViewById(R.id.fwbook_weiyixia);
        call = (TextView) findViewById(R.id.fwbook_call);
        fwpaytype = (TextView) findViewById(R.id.fwbook_paytype);
        fwpaytypet = (TextView) findViewById(R.id.fwbook_paytypet);
        fwpaytime = (TextView) findViewById(R.id.fwbook_paytime);
        fwpaytimet = (TextView) findViewById(R.id.fwbook_paytimet);
        fwbookbetween = (Button) findViewById(R.id.fwbook_betweenbt);
        fwbookright = (Button) findViewById(R.id.fwbook_rightbt);
        fwbookleft = (Button) findViewById(R.id.fwbook_leftbt);
        otherback.setOnClickListener(this);
        backmain.setOnClickListener(this);
        weiyuixia.setOnClickListener(this);
        call.setOnClickListener(this);
        fwbookbetween.setOnClickListener(this);
        fwbookleft.setOnClickListener(this);
        fwbookright.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.other_back:
                finish();
                break;
            case R.id.fwbookcontent_backmain:
                startActivity(new Intent(FWBookContentActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.fwbook_weiyixia:
                Toast.makeText(this, "功能建设中，敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.fwbook_call:
                if (from>20){
                    CallPhone.callPhone(FWBookContentActivity.this,contactPhone);
                }else {
                    CallPhone.callPhone(FWBookContentActivity.this,userMobile);
                }
                break;
            case R.id.fwbook_betweenbt:
               switch (from){
                   case 11:// 买家 待付款  删除订单
                       cancelService(id);
                       break;
                   case 12:// 买家 待服务 取消订单
                       cancelService(id);
                       break;
                   case 13:// 买家 服务中  申诉
                        appealService(id);
                       break;
                   case 14:// 买家 待完结 加价
                        addPriceFwBook();
                       break;
                   case 15:// 买家 已完结 申诉
                       appealService(id);
                       break;
                   case 16:// 买家 异常订单

                       break;
                   case 21:// 卖家 待服务 开始服务
                        addPriceFwBook();
                       break;
                   case 22:// 卖家 服务中 完成服务
                       addPriceFwBook();
                       break;
                   case 23:// 卖家 待完结 加价
                        appealService(id);
                       break;
                   case 24:// 卖家 已完结 申诉
                        appealService(id);
                       break;
                   case 25:// 卖家 异常订单

                       break;
               }
                break;
            case R.id.fwbook_rightbt:
                switch (from){
                    case 11:// 买家 待付款 支付
                        payFwBook(id);
                        break;
                    case 12:// 买家 待服务 加价
                        addPriceFwBook();
                        break;
                    case 13:// 买家 服务中 加价
                        addPriceFwBook();
                        break;
                    case 14:// 买家 待完结 服务完成
                        finishService(id);
                        break;
                    case 15:// 买家 已完结  评价
                        evaluateServicer(id);
                        break;
                    case 16:// 买家 异常订单 回复
                        Toast.makeText(this, "功能建设中，敬请期待", Toast.LENGTH_SHORT).show();
                        break;
                    case 21:// 卖家 待服务
                        beginService(id);
                        break;
                    case 22:// 卖家 服务中
                        overService(id);
                        break;
                    case 23:// 卖家 待完结
                        addPriceFwBook();
                        break;
                    case 24:// 卖家 已完结
                        Toast.makeText(this, "功能建设中，敬请期待", Toast.LENGTH_SHORT).show();
                        break;
                    case 25:// 卖家 异常订单
                        Toast.makeText(this, "功能建设中，敬请期待", Toast.LENGTH_SHORT).show();
                        break;
                }
                break;
            case R.id.fwbook_leftbt:
                switch (from){
                    case 11:// 买家 待付款

                        break;
                    case 12:// 买家 待服务

                        break;
                    case 13:// 买家 服务中

                        break;
                    case 14:// 买家 待完结 申诉
                        appealService(id);
                        break;
                    case 15:// 买家 已完结

                        break;
                    case 16:// 买家 异常订单

                        break;
                    case 21:// 卖家 待服务 取消订单
                      cancelService(id);
                        break;
                    case 22:// 卖家 服务中 申诉
                        appealService(id);
                        break;
                    case 23:// 卖家 待完结

                        break;
                    case 24:// 卖家 已完结

                        break;
                    case 25:// 卖家 异常订单

                        break;
                }
                break;
        }
    }

    // 取消订单
    private void cancelService(String id) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.CANCELSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);
        JSONObject object = new JSONObject();
        object.put("orderId",id);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 取消订单--"+result);
                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    finish();
                    Toast.makeText(FWBookContentActivity.this, "订单删除成功", Toast.LENGTH_SHORT).show();
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 取消订单--"+ex);
                ErrType.errType(FWBookContentActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    // 支付订单
    private void payFwBook(String id){

        Intent intent = new Intent(FWBookContentActivity.this,BookPayActivity.class);
        intent.putExtra("id",id);
        intent.putExtra("amount",totalAmount+"");
        intent.putExtra("from","buyservice");
        intent.putExtra("alipay",InternetAddressUtis.PAYALIBUYSERVICE);
        intent.putExtra("yivipay",InternetAddressUtis.PAYBUYSERVICE);
        startActivity(intent);
    }
    //订单加价
    private void addPriceFwBook(){

        // 提交成功支付
            AlertDialog.Builder builder = new AlertDialog.Builder(FWBookContentActivity.this);
            View view = LayoutInflater.from(FWBookContentActivity.this).inflate(R.layout.fw_addprice_dia, null);
            final EditText addprice = (EditText) view.findViewById(R.id.dia_addprice);
            TextView nowprice = (TextView) view.findViewById(R.id.dia_nowprice);
            nowprice.setText(totalAmount+"");
            Button cancel = (Button) view.findViewById(R.id.dia_addpricecancel);
            Button sure = (Button) view.findViewById(R.id.dia_addpricesure);
            builder.setView(view);
            final AlertDialog dialog = builder.create();
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String price = String.valueOf(addprice.getText());
                    if (from>20){//卖家
                        if (!price.equals("")){
                            vendorAddPrice(price,id);
                            dialog.dismiss();
                        }else {
                            Toast.makeText(FWBookContentActivity.this, "请输入加价金额", Toast.LENGTH_SHORT).show();
                        }
                    }else {//买家

                        if (!price.equals("")){
                            buyerAddPrice(price,id);
                            dialog.dismiss();
                        }else {
                            Toast.makeText(FWBookContentActivity.this, "请输入加价金额", Toast.LENGTH_SHORT).show();
                        }

                    }

                }
            });
            dialog.show();

    }

    //加价
    private void buyerAddPrice(final String price, final String id) {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETADDSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("orderId",id);
        object.put("amount",price);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 买家加价-"+result);
                JSONObject obj = JSON.parseObject(result);
                String data = obj.getString("data");
                String status = obj.getString("status");

                if (status.equals("1")){
                    Intent in = new Intent(FWBookContentActivity.this,BookPayActivity.class);
                    in.putExtra("from","fwadd");
                    in.putExtra("amount",price);
                    in.putExtra("id",data);
                    in.putExtra("alipay",InternetAddressUtis.ADDALIPAY);
                    in.putExtra("yivipay",InternetAddressUtis.ADDYIVIPAY);
                    startActivity(in);

                }else if (status.equals("0")){
                    String failure = obj.getString("failure");
                    Toast.makeText(FWBookContentActivity.this, "已申请加价，请等待对方回应", Toast.LENGTH_SHORT).show();
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 买家加价--"+ex);
                ErrType.errType(FWBookContentActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //加价
    private void vendorAddPrice(String price, String id) {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETADDSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("orderId",id);
        object.put("amount",price);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Toast.makeText(FWBookContentActivity.this, "加价成功请等待对方回应", Toast.LENGTH_SHORT).show();
                }else if (status.equals("0")){
                    String failure = obj.getString("failure");
                    if (failure.equals("1046")){
                        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(FWBookContentActivity.this,R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(FWBookContentActivity.this).inflate(R.layout.cancel_servicedialog, null);
                        builder.setView(view);
                        TextView t2 = (TextView) view.findViewById(R.id.cancel_t2);
                        Button surebt = (Button) view.findViewById(R.id.cancel_surebt);
                        Button cancelbt = (Button) view.findViewById(R.id.cancel_cancelbt);
                        t2.setText("您已申请过加价，请不要重复申请");
                        final android.support.v7.app.AlertDialog dialog = builder.create();
                        surebt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        cancelbt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                    }else {}
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    // 服务完成
    private void overService(String id) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.OVERSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("orderId",id);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 服务完成--"+result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(FWBookContentActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    // 卖家 开始服务
    private void beginService(String id) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.VENDORBEGINSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("orderId",id);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 开始服务--"+result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 开始服务--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    // 卖家 服务完结
    private void finishService(String id) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.FINISHSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("orderId",id);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Toast.makeText(FWBookContentActivity.this, "服务完成,请等待买家确认", Toast.LENGTH_SHORT).show();
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 服务完结--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    // 申诉订单
    private void appealService(String id){
        Intent intent = new Intent(FWBookContentActivity.this,FWHiteMeShopActivity.class);
        intent.putExtra("from","vendor");
        intent.putExtra("id",id);
        startActivity(intent);
    }
    //评价订单
    private void evaluateServicer(String id){
        Intent in = new Intent(FWBookContentActivity.this,FWEvaluateActivity.class);
        in.putExtra("id", id);
        in.putExtra("avatar",avatar);
        startActivity(in);
    }
}
